package com.lyz.service.impl;

import ch.qos.logback.core.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.lyz.domain.dto.BookPushDTO;
import com.lyz.domain.dto.BookQueryDTO;
import com.lyz.domain.entity.Book;
import com.lyz.mapper.BookMapper;
import com.lyz.service.IBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookService implements IBookService {
    @Autowired
    BookMapper bookMapper;

    @Override
    public boolean add(BookPushDTO bookPush) {
        Book book = new Book();
        BeanUtils.copyProperties(bookPush, book);
        book.setGmtCreate(LocalDateTime.now());
        book.setGmtModified(LocalDateTime.now());
        int res = bookMapper.insert(book);
        /* 库存+1 */
        return res > 0;
    }

    @Override
    public boolean remove(String isbn) {
        LambdaUpdateWrapper<Book> updateWrapper = new LambdaUpdateWrapper<Book>()
                .eq(Book::getIsbn, isbn);
        int res = bookMapper.delete(updateWrapper);
        return res > 0;
    }

    @Override
    public List<Book> find(BookQueryDTO bookQuery) {
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<Book>()
                .like(StringUtil.notNullNorEmpty(bookQuery.getName()),
                        Book::getName, bookQuery.getName())
                .eq(StringUtil.notNullNorEmpty(bookQuery.getAuthor()),
                        Book::getAuthor, bookQuery.getAuthor())
                .eq(StringUtil.notNullNorEmpty(bookQuery.getPress()),
                        Book::getPress, bookQuery.getPress());
        List<Book> books = bookMapper.selectList(queryWrapper);
        return books;
    }

    @Override
    public Book findByIsbn(String isbn) {
        return null;
    }
}
